import os
import sys

from simpledcpp.core.handlers.LoadFileList import SaxHandler
from simpledcpp.core.base import DCPPPart

from xml.sax import make_parser
try:
	from pyinotify import WatchManager, ThreadedNotifier, EventsCodes, ProcessEvent
	PYINOTIFY_ENABLED = True
except:
	PYINOTIFY_ENABLED = False

if PYINOTIFY_ENABLED:
    try:
        IN_CLOSE_WRITE = EventsCodes.IN_CLOSE_WRITE
    except AttributeError:
        from pyinotify import IN_CLOSE_WRITE


try:
	class FileEvents(ProcessEvent):
		""" Class for processing file events. """
	
		def __init__(self, EventFunction, *args, **kwargs):
			ProcessEvent.__init__(self, *args, **kwargs)
			self.__EventFunction = EventFunction
	
		def process_IN_CLOSE_WRITE(self, event):
			""" Function catch events, when file has been closed and may been writed.
			Call EventFunction. """
			try:
				self.__EventFunction(event)
			except:
				pass
except:
	class FileEvents:
		def __init__(self, *args, **kwargs):
			pass

class FileList(DCPPPart):

	def __init__(self, parent):
		DCPPPart.__init__(self, parent)
		filelist = {}
		filelisttth = {}
		self.__filename = None
		self.__filesize = None
		# Init pyinotify
		if PYINOTIFY_ENABLED:
			wm = WatchManager()
			mask = IN_CLOSE_WRITE
			self.notifier = ThreadedNotifier(wm, FileEvents(self.change))
			path_to_home = os.path.join(os.getenv("HOME"), ".simpledcpp/")
			wdd = wm.add_watch(path_to_home, mask, rec = False)
			self.notifier.start()

	def change(self, event):
		if event.name == 'files.xml.bz2':
			if self.__filesize != None and self.__filesize != os.path.getsize(self.__filename):
				self.Load(self.__filename)
				self.Notify("Filelist refreshed.", "Your filelist has been refreshed.")

	def stop(self, *args, **kwargs):
		if PYINOTIFY_ENABLED:
			self.notifier.stop()

	def Load(self, filename):
		self.__filename = filename
		self.__filesize = os.path.getsize(self.__filename)
		self._loadFileList(filename)
		for i in self.filelist:
			self.filelisttth[self.filelist[i][1]] = (i, self.filelist[i][0])
	
	def getRealName(self, filename):
		try:
			filename= filename.encode('utf-8')
		except:
			pass
		vdirname = filename.split('/',2)[1]
		dirs = self.parent.settings.get('shared_dirs').split(':')
		for i in range(0, len(dirs)/2):
			vroot = dirs[i*2]
			rroot = dirs[i*2 + 1]
			if vdirname == vroot:
				return rroot + '/' + filename.split('/',2)[2]
		return None

	def _loadFileList(self, filename):
		self.filelist = {}
		self.filelisttth = {}
                temp = '/tmp'
		if os.getenv('TEMP') != None and os.path.isdir(os.getenv('TEMP')):
			temp = os.getenv('TEMP')
		os.system('bzcat "%s" > %s/loadfilelist.tmp'%(filename,temp))
		curHandler = SaxHandler()
		parser = make_parser()
		parser.setContentHandler(curHandler)
		try:
			parser.parse(open('%s/loadfilelist.tmp'%temp))
		except IOError:
			print "Error while parsing %s"%('%s/loadfilelist.tmp'%temp)
		self.filelist = curHandler.filelist
		try:
			os.remove('%s/loadfilelist.tmp'%temp)
		except:
			pass

	def isExists(self, filename):
		if self.filelist.has_key(filename):
			return True
		else:
			return False
	
	def getInfo(self, filename):
		if self.isExists(filename):
			return self.filelist[filename]
		else:
			return None
	
	def getInfoByTTH(self, TTH):
		if self.filelisttth.has_key(TTH):
			return self.filelisttth[TTH]
		else:
			return None
